/**
 * Created by YHB on 2015/1/17.
 */
var mongoose = require('mongoose');
require('../../expansion/EModel.js');
var Store = mongoose.model('Store');
var Paper = mongoose.model('Paper');
var Question = mongoose.model('Question');
var Setting = require('../../models/setting.js');

var fs = require('fs');
var async = require('async');


function StoreService(){

}

/**
 *
 * 获取所有的题集
 * @param condition
 * @param pages
 * @param columns
 * @param sort
 * @param callback
 */
StoreService.prototype.getAllStore = function(condition, populate, pages, columns, sort, callback) {
    Store.findPagination(condition, populate, pages, columns, sort, callback);
}

/**
 * 保存store
 * @param content
 * @param callback
 */
StoreService.prototype.saveStore = function(content, callback){
    var store = new Store();
    store['active'] = true;
    store['category'] = content['category'];
    store['text'] = content['text'];
    store['drill'] = parseInt(content['drill']) || 2 ;
    store['score'] = parseInt(content['score']) || 5 ;
    store['duration'] = parseInt(content['duration']) || 60;
    store['profession'] = content['profession'];
    store['bounty'] = 0;
    store['bestScore'] = 0;
    store['bestUser'] = null;

    store.save(function(err, store){
        if(err) throw err;
        callback && callback(err, store);
    });
}


/**
 * 批量保存
 * @param content
 * @param callback
 */
StoreService.prototype.batchSaveQuestion = function (content, callback) {
    Question.create(content, function () {
        var error = arguments[0];
        if(error){ //判断err
            throw error;
        }
        var params = [];
        for (var i = 1, len = arguments.length; i < len; i++) {
            params.push(arguments[i]);
        }
        callback && callback(error, params);
    });
}


/**
 * 随机抽取一些题目保存在试卷中
 * @param store 题集
 * @param questions
 * @param callback
 * @param multiple //多选题的数量
 * @param single  //单选题的数量
 * @param judge  //判断题的数量
 */
StoreService.prototype.savePaper = function(store, questions, multiple, single, judge, callback){
    var paperNum = Setting.get('paperNum'); //随机的试卷数量
    var questionNum = Setting.get('questionNum'); //每套试卷的题目数量
    var questionItems = [];

    var mulQs = []; //单选
    var singQs = []; //多选
    var judgeQs = []; //判断

    for(var i=0;i<questions.length;i++){
        var question = questions[i];
        if(question.get('opts').length == 2){
            judgeQs.push(question);
        } else {
            if(question.get('answer').length > 1){
                mulQs.push(question);
            } else {
                singQs.push(question);
            }
        }
    }

    if(multiple > mulQs.length){
        multiple = mulQs.length;
    }

    if(single > singQs.length){
        single = singQs.length;
    }

    for (var i = 0; i < paperNum; i++) {
        //随机获得的题目
        var randomQuestions = randomForArr(singQs, single); //随机单选题
        var randomMulQ = randomForArr(mulQs, multiple);//随机多选题
        var randomJudgeQ = randomForArr(judgeQs, judge);//随机判断题
        var qs = randomMulQ.concat(randomQuestions);
        qs = qs.concat(randomJudgeQ);
        questionItems.push(qs);
    }

    async.eachSeries(questionItems, function(item, cb){
        var totalScore = 0;
        for (var i = 0, len = item.length; i < len; i++) {
            totalScore += parseInt(item[i]['score']);
        }
        var paper = {
            store: store,
            totalScore: totalScore,
            questions: item
        };
        Paper.create(paper, function (err, paper) {
            if(err) throw err;
            cb && cb(err, paper);
        });
    }, function (err, papers) {
        if(err) throw err;
        callback && callback(err, papers)
    })
}

/**
 *
 * @param store
 * @param content
 * @param callback
 */
StoreService.prototype.saveQuestion = function (store, content, callback) {
    var question = new Question();
    question['store'] = store;
    question['text'] = content['text'];
    question['score'] = parseInt(content['score']) || Setting.get('score');
    var answer = content['answer'] || [];
    answer = JSON.parse(JSON.stringify(answer).toUpperCase());
    question['answer'] = answer;
    question['opts'] = content['opts'];
    question.save(function (err, question) {
        if(err) throw err;
        callback && callback(err, question);
    });
}

StoreService.prototype.updateStore = function(data, where, callback){
    Store.findOneAndUpdate(where, data, function(err, res){
        callback && callback(err, res);
    })
}

StoreService.prototype.hideStore = function(data, where, callback){
    Store.findOneAndUpdate(where, data, function(err, res){
        callback && callback(err, res);
    })
}



module.exports = StoreService;

/**
 * 从一组数据中随机获取不重复的一组数据
 * @param arr
 * @param num
 * @returns {Array}
 */
var randomForArr = function(arr, num){
    //新建一个数组,将传入的数组复制过来,用于运算,而不要直接操作传入的数组;
    var temp_array = new Array();
    for (var index in arr) {
        temp_array.push(arr[index]);
    }
    //取出的数值项,保存在此数组
    var return_array = new Array();
    for (var i = 0; i<num; i++) {
        //判断如果数组还有可以取出的元素,以防下标越界
        if (temp_array.length>0) {
            //在数组中产生一个随机索引
            var arrIndex = Math.floor(Math.random()*temp_array.length);
            //将此随机索引的对应的数组元素值复制出来
            return_array[i] = temp_array[arrIndex];
            //然后删掉此索引的数组元素,这时候temp_array变为新的数组
            temp_array.splice(arrIndex, 1);
        } else {
            //数组中数据项取完后,退出循环,比如数组本来只有10项,但要求取出20项.
            break;
        }
    }
    return return_array;
}